import React, { useState, useCallback } from 'react'
import { X, User, Lock, Mail, AlertCircle, Eye, EyeOff, CheckCircle } from 'lucide-react'
import { useAuth } from '../../contexts/AuthProvider'
import { LoginFormData, SignUpFormData } from '../../types/auth'

interface LoginDialogProps {
  isOpen: boolean
  onClose: () => void
  defaultMode?: 'login' | 'signup' | 'reset'
  redirectUrl?: string
}

export function LoginDialog({ isOpen, onClose, defaultMode = 'login', redirectUrl }: LoginDialogProps) {
  const [mode, setMode] = useState<'login' | 'signup' | 'reset' | 'success'>(defaultMode)
  const [loading, setLoading] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  
  const { signIn, signUp, resetPassword } = useAuth()

  // Login form state
  const [loginData, setLoginData] = useState<LoginFormData>({
    email: '',
    password: '',
    rememberMe: false
  })

  // Signup form state
  const [signupData, setSignupData] = useState<SignUpFormData>({
    email: '',
    password: '',
    confirmPassword: '',
    fullName: '',
    displayName: '',
    gdprConsent: false,
    marketingConsent: false,
    termsAccepted: false
  })

  // Reset password form state
  const [resetEmail, setResetEmail] = useState('')

  // Clear form data and errors
  const clearForms = useCallback(() => {
    setLoginData({
      email: '',
      password: '',
      rememberMe: false
    })
    setSignupData({
      email: '',
      password: '',
      confirmPassword: '',
      fullName: '',
      displayName: '',
      gdprConsent: false,
      marketingConsent: false,
      termsAccepted: false
    })
    setResetEmail('')
    setErrors({})
    setShowPassword(false)
    setShowConfirmPassword(false)
  }, [])

  const handleClose = useCallback(() => {
    clearForms()
    setMode(defaultMode)
    onClose()
  }, [clearForms, defaultMode, onClose])

  // Validation functions
  const validateEmail = (email: string): string | null => {
    if (!email) return 'Email is required'
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(email)) return 'Please enter a valid email address'
    return null
  }

  const validatePassword = (password: string): string | null => {
    if (!password) return 'Password is required'
    if (password.length < 8) return 'Password must be at least 8 characters'
    if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
      return 'Password must contain at least one lowercase letter, one uppercase letter, and one number'
    }
    return null
  }

  const validateSignupForm = (): boolean => {
    const newErrors: Record<string, string> = {}

    const emailError = validateEmail(signupData.email)
    if (emailError) newErrors.email = emailError

    const passwordError = validatePassword(signupData.password)
    if (passwordError) newErrors.password = passwordError

    if (signupData.password !== signupData.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match'
    }

    if (!signupData.fullName.trim()) {
      newErrors.fullName = 'Full name is required'
    }

    if (!signupData.gdprConsent) {
      newErrors.gdprConsent = 'You must consent to data processing'
    }

    if (!signupData.termsAccepted) {
      newErrors.termsAccepted = 'You must accept the terms and conditions'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  // Handle login
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    const newErrors: Record<string, string> = {}

    const emailError = validateEmail(loginData.email)
    if (emailError) newErrors.email = emailError

    if (!loginData.password) newErrors.password = 'Password is required'

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors)
      return
    }

    setLoading(true)
    setErrors({})

    try {
      await signIn(loginData.email, loginData.password, loginData.rememberMe)
      handleClose()
      if (redirectUrl) {
        window.location.href = redirectUrl
      }
    } catch (error: any) {
      setErrors({ 
        form: error.message || 'Login failed. Please check your credentials.'
      })
    } finally {
      setLoading(false)
    }
  }

  // Handle signup
  const handleSignup = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!validateSignupForm()) return

    setLoading(true)
    setErrors({})

    try {
      await signUp(signupData.email, signupData.password, {
        full_name: signupData.fullName,
        display_name: signupData.displayName || signupData.fullName,
        gdpr_consent: signupData.gdprConsent,
        notification_preferences: {
          email_notifications: signupData.marketingConsent,
          weekly_digest: signupData.marketingConsent,
          instant_alerts: false,
          paper_recommendations: signupData.marketingConsent,
          new_category_papers: false,
          author_updates: false,
          keyword_matches: false,
          push_notifications: false,
          sms_notifications: false,
          digest_frequency: 'weekly',
          quiet_hours: {
            enabled: false,
            start_time: '22:00',
            end_time: '08:00'
          }
        }
      })
      setMode('success')
    } catch (error: any) {
      setErrors({ 
        form: error.message || 'Registration failed. Please try again.'
      })
    } finally {
      setLoading(false)
    }
  }

  // Handle password reset
  const handleResetPassword = async (e: React.FormEvent) => {
    e.preventDefault()
    
    const emailError = validateEmail(resetEmail)
    if (emailError) {
      setErrors({ email: emailError })
      return
    }

    setLoading(true)
    setErrors({})

    try {
      await resetPassword(resetEmail)
      setMode('success')
    } catch (error: any) {
      setErrors({ 
        form: error.message || 'Password reset failed. Please try again.'
      })
    } finally {
      setLoading(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-gray-800">
            {mode === 'login' && 'Sign In'}
            {mode === 'signup' && 'Create Account'}
            {mode === 'reset' && 'Reset Password'}
            {mode === 'success' && 'Success!'}
          </h2>
          <button
            onClick={handleClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X size={24} />
          </button>
        </div>

        {errors.form && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md flex items-center">
            <AlertCircle className="text-red-500 mr-2" size={18} />
            <p className="text-red-600 text-sm">{errors.form}</p>
          </div>
        )}

        {/* Login Form */}
        {mode === 'login' && (
          <form onSubmit={handleLogin} className="space-y-4">
            <div>
              <label htmlFor="login-email" className="block text-sm font-medium text-gray-700 mb-2">
                Email Address
              </label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="email"
                  id="login-email"
                  value={loginData.email}
                  onChange={(e) => setLoginData(prev => ({ ...prev, email: e.target.value }))}
                  placeholder="Enter your email"
                  className={`w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.email ? 'border-red-300' : 'border-gray-300'
                  }`}
                  disabled={loading}
                />
              </div>
              {errors.email && <p className="text-red-600 text-sm mt-1">{errors.email}</p>}
            </div>

            <div>
              <label htmlFor="login-password" className="block text-sm font-medium text-gray-700 mb-2">
                Password
              </label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type={showPassword ? 'text' : 'password'}
                  id="login-password"
                  value={loginData.password}
                  onChange={(e) => setLoginData(prev => ({ ...prev, password: e.target.value }))}
                  placeholder="Enter your password"
                  className={`w-full pl-10 pr-10 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.password ? 'border-red-300' : 'border-gray-300'
                  }`}
                  disabled={loading}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                </button>
              </div>
              {errors.password && <p className="text-red-600 text-sm mt-1">{errors.password}</p>}
            </div>

            <div className="flex items-center justify-between">
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={loginData.rememberMe}
                  onChange={(e) => setLoginData(prev => ({ ...prev, rememberMe: e.target.checked }))}
                  className="mr-2"
                />
                <span className="text-sm text-gray-600">Remember me</span>
              </label>
              <button
                type="button"
                onClick={() => setMode('reset')}
                className="text-sm text-blue-600 hover:text-blue-800"
              >
                Forgot password?
              </button>
            </div>

            <button
              type="submit"
              className="w-full px-4 py-2 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-md hover:from-blue-600 hover:to-purple-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              disabled={loading}
            >
              {loading ? 'Signing in...' : 'Sign In'}
            </button>

            <div className="text-center">
              <button
                type="button"
                onClick={() => setMode('signup')}
                className="text-blue-600 hover:text-blue-800 text-sm"
              >
                Don't have an account? Sign up
              </button>
            </div>
          </form>
        )}

        {/* Signup Form */}
        {mode === 'signup' && (
          <form onSubmit={handleSignup} className="space-y-4">
            <div>
              <label htmlFor="signup-email" className="block text-sm font-medium text-gray-700 mb-2">
                Email Address <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="email"
                  id="signup-email"
                  value={signupData.email}
                  onChange={(e) => setSignupData(prev => ({ ...prev, email: e.target.value }))}
                  placeholder="Enter your email"
                  className={`w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.email ? 'border-red-300' : 'border-gray-300'
                  }`}
                  disabled={loading}
                />
              </div>
              {errors.email && <p className="text-red-600 text-sm mt-1">{errors.email}</p>}
            </div>

            <div>
              <label htmlFor="signup-fullname" className="block text-sm font-medium text-gray-700 mb-2">
                Full Name <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="text"
                  id="signup-fullname"
                  value={signupData.fullName}
                  onChange={(e) => setSignupData(prev => ({ ...prev, fullName: e.target.value }))}
                  placeholder="Enter your full name"
                  className={`w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.fullName ? 'border-red-300' : 'border-gray-300'
                  }`}
                  disabled={loading}
                />
              </div>
              {errors.fullName && <p className="text-red-600 text-sm mt-1">{errors.fullName}</p>}
            </div>

            <div>
              <label htmlFor="signup-password" className="block text-sm font-medium text-gray-700 mb-2">
                Password <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type={showPassword ? 'text' : 'password'}
                  id="signup-password"
                  value={signupData.password}
                  onChange={(e) => setSignupData(prev => ({ ...prev, password: e.target.value }))}
                  placeholder="Create a password"
                  className={`w-full pl-10 pr-10 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.password ? 'border-red-300' : 'border-gray-300'
                  }`}
                  disabled={loading}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                </button>
              </div>
              {errors.password && <p className="text-red-600 text-sm mt-1">{errors.password}</p>}
            </div>

            <div>
              <label htmlFor="signup-confirm-password" className="block text-sm font-medium text-gray-700 mb-2">
                Confirm Password <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type={showConfirmPassword ? 'text' : 'password'}
                  id="signup-confirm-password"
                  value={signupData.confirmPassword}
                  onChange={(e) => setSignupData(prev => ({ ...prev, confirmPassword: e.target.value }))}
                  placeholder="Confirm your password"
                  className={`w-full pl-10 pr-10 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.confirmPassword ? 'border-red-300' : 'border-gray-300'
                  }`}
                  disabled={loading}
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                </button>
              </div>
              {errors.confirmPassword && <p className="text-red-600 text-sm mt-1">{errors.confirmPassword}</p>}
            </div>

            <div className="space-y-3">
              <label className="flex items-start">
                <input
                  type="checkbox"
                  checked={signupData.gdprConsent}
                  onChange={(e) => setSignupData(prev => ({ ...prev, gdprConsent: e.target.checked }))}
                  className="mr-2 mt-1"
                />
                <span className="text-sm text-gray-600">
                  I consent to the processing of my personal data for the purposes of using this service. <span className="text-red-500">*</span>
                </span>
              </label>
              {errors.gdprConsent && <p className="text-red-600 text-sm">{errors.gdprConsent}</p>}

              <label className="flex items-start">
                <input
                  type="checkbox"
                  checked={signupData.termsAccepted}
                  onChange={(e) => setSignupData(prev => ({ ...prev, termsAccepted: e.target.checked }))}
                  className="mr-2 mt-1"
                />
                <span className="text-sm text-gray-600">
                  I agree to the <a href="/terms" className="text-blue-600 hover:text-blue-800">Terms of Service</a> and <a href="/privacy" className="text-blue-600 hover:text-blue-800">Privacy Policy</a>. <span className="text-red-500">*</span>
                </span>
              </label>
              {errors.termsAccepted && <p className="text-red-600 text-sm">{errors.termsAccepted}</p>}

              <label className="flex items-start">
                <input
                  type="checkbox"
                  checked={signupData.marketingConsent}
                  onChange={(e) => setSignupData(prev => ({ ...prev, marketingConsent: e.target.checked }))}
                  className="mr-2 mt-1"
                />
                <span className="text-sm text-gray-600">
                  I would like to receive email notifications about new papers and updates.
                </span>
              </label>
            </div>

            <button
              type="submit"
              className="w-full px-4 py-2 bg-gradient-to-r from-green-500 to-blue-600 text-white rounded-md hover:from-green-600 hover:to-blue-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              disabled={loading}
            >
              {loading ? 'Creating account...' : 'Create Account'}
            </button>

            <div className="text-center">
              <button
                type="button"
                onClick={() => setMode('login')}
                className="text-blue-600 hover:text-blue-800 text-sm"
              >
                Already have an account? Sign in
              </button>
            </div>
          </form>
        )}

        {/* Password Reset Form */}
        {mode === 'reset' && (
          <form onSubmit={handleResetPassword} className="space-y-4">
            <div className="text-center mb-4">
              <p className="text-gray-600 text-sm">
                Enter your email address and we'll send you instructions to reset your password.
              </p>
            </div>

            <div>
              <label htmlFor="reset-email" className="block text-sm font-medium text-gray-700 mb-2">
                Email Address
              </label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="email"
                  id="reset-email"
                  value={resetEmail}
                  onChange={(e) => setResetEmail(e.target.value)}
                  placeholder="Enter your email"
                  className={`w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                    errors.email ? 'border-red-300' : 'border-gray-300'
                  }`}
                  disabled={loading}
                />
              </div>
              {errors.email && <p className="text-red-600 text-sm mt-1">{errors.email}</p>}
            </div>

            <button
              type="submit"
              className="w-full px-4 py-2 bg-gradient-to-r from-purple-500 to-pink-600 text-white rounded-md hover:from-purple-600 hover:to-pink-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              disabled={loading}
            >
              {loading ? 'Sending...' : 'Send Reset Instructions'}
            </button>

            <div className="text-center">
              <button
                type="button"
                onClick={() => setMode('login')}
                className="text-blue-600 hover:text-blue-800 text-sm"
              >
                Back to sign in
              </button>
            </div>
          </form>
        )}

        {/* Success Message */}
        {mode === 'success' && (
          <div className="text-center space-y-4">
            <div className="flex justify-center">
              <CheckCircle className="text-green-500" size={48} />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-800 mb-2">Success!</h3>
              <p className="text-gray-600 text-sm">
                {defaultMode === 'signup' 
                  ? 'Your account has been created successfully. Please check your email to verify your account.'
                  : 'Password reset instructions have been sent to your email address.'
                }
              </p>
            </div>
            <button
              onClick={handleClose}
              className="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
            >
              Continue
            </button>
          </div>
        )}
      </div>
    </div>
  )
}